package com.icesoft.core.web.suppose.safehttp.request;

import com.icesoft.core.web.helper.RequestHold;
import com.icesoft.core.web.suppose.safehttp.filter.SafeRequestCryptoService;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

@Slf4j
public class RequestSettingFilter implements Filter {
    private SafeRequestCryptoService safeRequestCryptoService;

    public RequestSettingFilter(SafeRequestCryptoService safeRequestCryptoService) {
        this.safeRequestCryptoService = safeRequestCryptoService;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        if (log.isTraceEnabled() || (log.isDebugEnabled() && "true".equals(request.getHeader("logRequest")))) {
            Enumeration<String> headers = request.getHeaderNames();
            StringBuilder sb = new StringBuilder("remote ip:" + RequestHold.getRemoteIP(request)).append("\n");
            sb.append("请求 url: " + request.getRequestURI()).append("\n");
            sb.append("----------request headers---------- \n");
            while (headers.hasMoreElements()) {
                String name = headers.nextElement();
                String val = request.getHeader(name);
                sb.append(name).append(" = ").append(val).append("\n");
            }
            sb.append("----------request params---------- \n");
            RequestHold.getRequestParamMap(request).forEach((key, val) -> {
                sb.append(key).append(" = ").append(val).append("\n");
            });
            sb.append("正式环境请不要添加该请求头logRequest，否则将导致日志文件过大");
            if (log.isTraceEnabled()) {
                log.trace(sb.toString());
            } else {
                log.debug(sb.toString());
            }
        }
        chain.doFilter(new SafeHttpServletRequest(safeRequestCryptoService, request), response);
    }

}
